package com.glory.cqaospda.view

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.NfcA
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.Settings
import android.view.KeyEvent
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.glory.cqaospda.R
import com.glory.cqaospda.adapter.DialogAdapter
import com.glory.cqaospda.adapter.LotAdapter
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.bean.*
import com.glory.cqaospda.utils.ByteArrayChange
import com.glory.cqaospda.utils.EditTextEnterUtils
import com.glory.cqaospda.viewmodel.Repair2ItemModel
import com.glory.mvvmnet.base.BaseActivity
import com.glory.mvvmnet.entity.ToastMessageBean
import com.glorysoft.hlgdpda.utils.PopWindowsUtils
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText
import kotlinx.android.synthetic.main.activity_repair2.*
import kotlinx.android.synthetic.main.activity_repair2item.*
import kotlinx.android.synthetic.main.activity_repair2item.etLotId
import kotlinx.android.synthetic.main.activity_repair2item.etWorkCard
import kotlinx.android.synthetic.main.activity_repair2item.ivTypeArrow
import kotlinx.android.synthetic.main.activity_startjob.*
import kotlinx.android.synthetic.main.activity_title.*

class Repair2ItemActivity : BaseActivity<Repair2ItemModel>(), View.OnClickListener {

    var mNfcAdapter: NfcAdapter? = null
    var mPendingIntent: PendingIntent? = null
    lateinit var mFilters: Array<IntentFilter>
    lateinit var mTechLists: Array<Array<String>>
    private var codePop: PopWindowsUtils.GeneralPop? = null
    lateinit var itemList: MaintenanceBean.ItemList
    var list: ArrayList<String> = ArrayList()
    var maintainResults = "0"
    var isGroupName = false
    var checkBoxList = ArrayList<CheckBoxList>()
    var checkBoxListBean1 = CheckBoxList()
    var checkBoxListBean2 = CheckBoxList()
    var checkBoxListBean3 = CheckBoxList()
    var checkBoxListBean4 = CheckBoxList()
    var checkBoxListBean5 = CheckBoxList()
    var mLotAdapter: LotAdapter? = null
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@Repair2ItemActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }
    var listQty = arrayListOf(
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "10",
        "11",
        "12",
        "13",
        "14",
        "15",
        "16",
        "17",
        "18",
        "19",
        "20"
    )

    override fun initData() {

        checkNFCFunction()
        mPendingIntent = PendingIntent.getActivity(
            this, 0, Intent(
                this,
                javaClass
            ).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)
        // Setup an intent filter for all MIME based dispatches
        val ndef = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
        try {
            ndef.addDataType("*/*")
        } catch (e: IntentFilter.MalformedMimeTypeException) {
            throw RuntimeException("fail", e)
        }
        mFilters = arrayOf(ndef)

        // 根据标签类型设置
        mTechLists = arrayOf(arrayOf(NfcA::class.java.name))

        flBuyoffType.setOnClickListener {
            codePop = PopWindowsUtils.getOneChoosePop(this, flBuyoffType.width, listQty,
                ivBuyoffTypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                    override fun onSuccess(string: String, potion: Int) {
                        tvBuyoffType.text = string
                        checkBoxListBean1.maintenanceValue = tvBuyoffType.text.toString()
                    }
                }
            )
            if (codePop!!.isShowing) {
                codePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivBuyoffTypeArrow)
                codePop?.showAsDropDown(flBuyoffType, 0, 0)
            }
        }
        flQuanType.setOnClickListener {
            codePop = PopWindowsUtils.getOneChoosePop(this, flQuanType.width, listQty,
                ivQuanTypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                    override fun onSuccess(string: String, potion: Int) {
                        tvQuanType.text = string
                        checkBoxListBean2.maintenanceValue = tvQuanType.text.toString()
                    }
                }
            )
            if (codePop!!.isShowing) {
                codePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivQuanTypeArrow)
                codePop?.showAsDropDown(flQuanType, 0, 0)
            }
        }
        flQAType.setOnClickListener {
            codePop = PopWindowsUtils.getOneChoosePop(this, flQAType.width, listQty,
                ivQATypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                    override fun onSuccess(string: String, potion: Int) {
                        tvQAType.text = string
                        checkBoxListBean3.maintenanceValue = tvQAType.text.toString()
                    }
                }
            )
            if (codePop!!.isShowing) {
                codePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivQATypeArrow)
                codePop?.showAsDropDown(flQAType, 0, 0)
            }
        }
        flpeelingType.setOnClickListener {
            codePop = PopWindowsUtils.getOneChoosePop(this, flpeelingType.width, listQty,
                ivpeelingTypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                    override fun onSuccess(string: String, potion: Int) {
                        tvpeelingType.text = string
                        checkBoxListBean4.maintenanceValue = tvpeelingType.text.toString()
                    }
                }
            )
            if (codePop!!.isShowing) {
                codePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivpeelingTypeArrow)
                codePop?.showAsDropDown(flpeelingType, 0, 0)
            }
        }
        flbinType.setOnClickListener {
            codePop = PopWindowsUtils.getOneChoosePop(this, flbinType.width, listQty,
                ivbinTypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                    override fun onSuccess(string: String, potion: Int) {
                        tvbinType.text = string
                        checkBoxListBean5.maintenanceValue = tvbinType.text.toString()
                    }
                }
            )
            if (codePop!!.isShowing) {
                codePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivbinTypeArrow)
                codePop?.showAsDropDown(flbinType, 0, 0)
            }
        }
    }

    protected fun initRecyclerView(recyclerView: RecyclerView, context: Context?) {
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.itemAnimator = DefaultItemAnimator()
        recyclerView.addItemDecoration(DividerItemDecoration(context, 1))
    }

    override fun initView(savedInstanceState: Bundle?) {

//        tvBaseSubmit.text = "更换配件"
        tvBaseSubmit.visibility = View.GONE
        tvTitle.text = "维修结论"

        tvUserName.text = Constant.UserName
        FreeApi_ActivityManager.getActivityManager().addActivity(this)

        val instance = MyApp.instance
        instance!!.handler = handler
        mLotAdapter = LotAdapter(null)
        initRecyclerView(rvLotList, this)
        rvLotList.adapter = mLotAdapter

        itemList = intent.getSerializableExtra("itemList") as MaintenanceBean.ItemList
        tvEquipmentName.text = itemList.mEquipmentName
        tvMaintenanceItem.text = itemList.mMaintenanceItem
        etLotId.setText(itemList.mLotNo)

        viewModel.defaultGetBaseConfig()

        viewModel.defUI.callObserve.observe(this@Repair2ItemActivity) {
            if (!Constant.okgoError) {
                when (it.type) {
                    1 -> {
                        list.clear()
                        val baseConfigBean = it.item as BaseConfigBean
                        for (item in baseConfigBean.mItemList) {
                            list.add(item.mItemValue)
                        }
                    }
                    2 -> {
                        if (isGroupName){
                            viewModel.defUI.toastEvent.value = ToastMessageBean("切换维修组成功", true)
                        }else{
                            viewModel.defUI.toastEvent.value = ToastMessageBean("提交成功", true)
                        }
                        intent.setClass(this, HomeActivity::class.java)
                        startActivity(intent)
                        finish()
                    }
                }
            } else {
                Constant.okgoError = false
            }
        }

        rbmaintainResults0.setOnClickListener(this)
        rbmaintainResults1.setOnClickListener(this)
        rbmaintainResults2.setOnClickListener(this)
        rbmaintainResults3.setOnClickListener(this)
        cbMaintainVerification0.setOnClickListener(this)
        cbMaintainVerification1.setOnClickListener(this)
        cbMaintainVerification2.setOnClickListener(this)
        cbMaintainVerification3.setOnClickListener(this)
        cbMaintainVerification4.setOnClickListener(this)
        rbisPartsY.setOnClickListener(this)
        rbisPartsN.setOnClickListener(this)

//        initEdit(etLotID)
        queryEqpData(etPartsID)
//        val dialogAdapter = DialogAdapter(null)
//        rvLotList.layoutManager = LinearLayoutManager(this)
//        rvLotList.adapter = dialogAdapter
//        dialogAdapter.addData(DialogLotBean())

        flPositionList.setOnClickListener {
            codePop = PopWindowsUtils.getOneChoosePop(this, flType.width, list,
                ivTypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                    override fun onSuccess(string: String, potion: Int) {
                        tvType.text = string
                    }
                }
            )

            if (codePop!!.isShowing) {
                codePop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivTypeArrow)
                codePop?.showAsDropDown(flType, 0, 0)
            }
        }

//        tvBaseSubmit.setOnClickListener{
//            intent.putExtra("type", "LotID")
//            intent.putExtra("types", "repair")
//            intent.setClass(this, SkipDialogActivity::class.java)
//            startActivity(intent)
//        }

        btSwitchGroupName.setOnClickListener {
            isGroupName = true
            var groupName = ""
            when(itemList.mGroupName){
                "PE" ->{
                    groupName = "ME"
                }
                "ME" ->{
                    groupName = "PE"
                }
            }
            val map = JsonObject()
            map.addProperty("UserName", itemList.mUserName)
            map.addProperty("OrderID", itemList.mOrderID)
            map.addProperty("GroupName", groupName)
            map.addProperty("MaintainType", "1")
            viewModel.defaultMaintenanceOrder(map)
        }

        btnRepair2.setOnClickListener {
            isGroupName = false
            if (Constant.isFastClick()) {
                if (etWorkCard.text.toString() == "" && rbmaintainResults0.isChecked) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("工卡卡号不能为空", false)
                    return@setOnClickListener
                }

                if (tvType.text.toString() == "") {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请选择维修内容", false)
                    return@setOnClickListener
                }

                if (maintainResults == "3" && etLotId.text.toString() == "") {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请扫描LotID", false)
                    return@setOnClickListener
                }
                if (rbisPartsY.isChecked) {
                    if (mLotAdapter!!.data.size == 0) {
                        viewModel.defUI.toastEvent.value = ToastMessageBean("请扫描配件ID", false)
                        return@setOnClickListener
                    }
                }

                val map = JsonObject()
                map.addProperty("UserName", itemList.mUserName)
                map.addProperty("OrderID", itemList.mOrderID)
                map.addProperty("MaintainType", "1")
                map.addProperty("EquipmentName", itemList.mEquipmentName)
                map.addProperty("LotNo", etLotId.text.toString())
                map.addProperty("MaintainContent", tvType.text.toString())
                map.addProperty("MaintainResults", maintainResults)
                map.addProperty("Comment", etComment.text.toString())
                map.addProperty("WorkCardID", etWorkCard.text.toString())
                val partsIDList = ArrayList<LotList>()
                for (s in mLotAdapter!!.data) {
                    val lotList = LotList()
                    lotList.partsID = s
                    partsIDList.add(lotList)
                }
                map.add(
                    "PartsList",
                    JsonParser().parse(Gson().toJson(partsIDList)).asJsonArray
                )
                map.add(
                    "MaintenanceItemList",
                    JsonParser().parse(Gson().toJson(checkBoxList)).asJsonArray
                )
                viewModel.defaultMaintenanceOrder(map)
            }
        }

//        ivAddLot.setOnClickListener {
//            dialogAdapter.addData(DialogLotBean())
//        }
//        ivRemoveLot.setOnClickListener {
//            if (dialogAdapter.data.size == 1) {
//
//            } else {
//                dialogAdapter.data.removeAt(dialogAdapter.data.size - 1)
//                dialogAdapter.notifyDataSetChanged()
//            }
//        }

    }

    private fun getLot(dialogAdapter: DialogAdapter): ArrayList<LotList> {
        val partsIDList = ArrayList<LotList>()
//        val lotList = LotList()
//        lotList.partsID = etLot.text.toString()
//        partsIDList.add(lotList)
        for (datum in dialogAdapter.data) {
            if (datum.Lot != null) {
                val lotList = LotList()
                lotList.partsID = datum.Lot
                partsIDList.add(lotList)
            }
        }
        return partsIDList
    }

    override fun layoutId(): Int {
        return R.layout.activity_repair2item
    }

    override fun onClick(view: View?) {
        when (view!!.id) {
            R.id.rbmaintainResults0 -> {
                maintainResults = "0"
            }
            R.id.rbmaintainResults1 -> {
                maintainResults = "1"
            }
            R.id.rbmaintainResults2 -> {
                maintainResults = "2"
            }
            R.id.rbmaintainResults3 -> {
                maintainResults = "3"
            }
            R.id.rbisPartsY -> {
                llParts.visibility = View.VISIBLE
                llPartsTitle.visibility = View.VISIBLE
                rvLotList.visibility = View.VISIBLE
            }
            R.id.rbisPartsN -> {
                llParts.visibility = View.GONE
                llPartsTitle.visibility = View.GONE
                rvLotList.visibility = View.GONE
            }

            R.id.cbMaintainVerification0 -> {
                if (cbMaintainVerification0.isChecked) {
                    flBuyoffType.visibility = View.VISIBLE
                    checkBoxListBean1.maintenanceKey = "0"
                    checkBoxListBean1.maintenanceValue = tvBuyoffType.text.toString()
                    checkBoxList.add(checkBoxListBean1)
                } else {
                    flBuyoffType.visibility = View.GONE
                    checkBoxList.remove(checkBoxListBean1)
                }
            }

            R.id.cbMaintainVerification1 -> {
                if (cbMaintainVerification1.isChecked) {
                    flQuanType.visibility = View.VISIBLE
                    checkBoxListBean2.maintenanceKey = "1"
                    checkBoxListBean2.maintenanceValue = tvQuanType.text.toString()
                    checkBoxList.add(checkBoxListBean2)
                } else {
                    flQuanType.visibility = View.GONE
                    checkBoxList.remove(checkBoxListBean2)
                }
            }
            R.id.cbMaintainVerification2 -> {
                if (cbMaintainVerification2.isChecked) {
                    flQAType.visibility = View.VISIBLE
                    checkBoxListBean3.maintenanceKey = "2"
                    checkBoxListBean3.maintenanceValue = tvQAType.text.toString()
                    checkBoxList.add(checkBoxListBean3)
                } else {
                    flQAType.visibility = View.GONE
                    checkBoxList.remove(checkBoxListBean3)
                }
            }
            R.id.cbMaintainVerification3 -> {
                if (cbMaintainVerification3.isChecked) {
                    flpeelingType.visibility = View.VISIBLE
                    checkBoxListBean4.maintenanceKey = "3"
                    checkBoxListBean4.maintenanceValue = tvpeelingType.text.toString()
                    checkBoxList.add(checkBoxListBean4)
                } else {
                    flpeelingType.visibility = View.GONE
                    checkBoxList.remove(checkBoxListBean4)
                }
            }
            R.id.cbMaintainVerification4 -> {
                if (cbMaintainVerification4.isChecked) {
                    flbinType.visibility = View.VISIBLE
                    checkBoxListBean5.maintenanceKey = "4"
                    checkBoxListBean5.maintenanceValue = tvbinType.text.toString()
                    checkBoxList.add(checkBoxListBean5)
                } else {
                    flbinType.visibility = View.GONE
                    checkBoxList.remove(checkBoxListBean5)
                }
            }
        }
    }

    private fun queryEqpData(
        editText: FreeUI_ClearEditText?,
    ) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            for (entity in mLotAdapter!!.data) {
                if (s.equals(entity)) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("当前配件ID以添加", true)
                    return@setEditTextListener
                }
            }
            mLotAdapter!!.addData(s)
            etPartsID.setText("")
            val handler = Handler()
            handler.postDelayed({ etPartsID.requestFocus() }, 500)
        }

    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1) {
            when (resultCode) {
                108 -> {
                    finish()
                }
            }
        }
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            intent.putExtra("type", "KeyEvent")
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivityForResult(intent, 1)
            return false
        }
        return super.onKeyUp(keyCode, event)
    }

    private fun checkNFCFunction() {
        // TODO Auto-generated method stub
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this)
        // check the NFC adapter first
        if (mNfcAdapter == null) {

            FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "该设备未发现NFC功能", {

            }) {}.show(supportFragmentManager, "SUBMIT_DIALOG")

            return
        } else {
            if (!mNfcAdapter!!.isEnabled) {

                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "NFC未开启,是否去开启？", {

                    val setnfc = Intent(
                        Settings.ACTION_NFC_SETTINGS
                    )
                    startActivity(setnfc)

                }) {}.show(supportFragmentManager, "SUBMIT_DIALOG")
                return
            }
        }
    }
    override fun onResume() {
        super.onResume()
        enableForegroundDispatch()
    }

    private fun enableForegroundDispatch() {
        // TODO 自动生成的方法存根
        if (mNfcAdapter != null) {
            mNfcAdapter!!.enableForegroundDispatch(
                this, mPendingIntent,
                mFilters, mTechLists
            )
        }
    }
    override fun onNewIntent(intent: Intent) {
        // TODO 自动生成的方法存根
        super.onNewIntent(intent)
        val intentActionStr = intent.action // 获取到本次启动的action
        if (NfcAdapter.ACTION_NDEF_DISCOVERED == intentActionStr || NfcAdapter.ACTION_TECH_DISCOVERED == intentActionStr || NfcAdapter.ACTION_TAG_DISCOVERED == intentActionStr) { // 未知类型
            // 在intent中读取Tag id
            val tag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
            val bytesId = tag!!.id // 获取id数组
            val cardid = ByteArrayChange.ByteArrayToHexString(bytesId).toString()
            if (cardid == "") {
                viewModel.defUI.toastEvent.value = ToastMessageBean("未读取到信息", false)
                return
            }
            etWorkCard.setText(cardid)
        }
    }
}